package main.编程题;

import java.util.Map;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author tmh
 * @date 2024/8/1 17:18
 * @description
 */
public class T线程交替打印奇偶数ReetrantLock_condition {
    private static final Lock lock = new ReentrantLock();
    private static final Condition oddCondition = lock.newCondition();
    private static final Condition evenCondition = lock.newCondition();

    private static int number = 1;
    private static int MAX_NUMBER = 100;

    public static void main(String[] args) {
        Thread oddThread = new Thread(() -> {
            while (number < MAX_NUMBER) {
                lock.lock();
                try {
                    //偶数的逻辑
                    if (number % 2 == 0) {
                        //那么就调用这个oddCondition的await方法
                        oddCondition.await();
                    }
                    System.out.println("奇数：" + number);
                    number++;
                    //唤醒另一个线程
                    evenCondition.signal();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                } finally {
                    lock.unlock();
                }
            }
        });
        Thread evenThread = new Thread(() -> {
            while (number < MAX_NUMBER) {
                lock.lock();
                try {
                    if (number % 2 != 0) {
                        //奇数的逻辑，阻塞当前线程
                        evenCondition.await();
                    }
                    //偶数的逻辑完了之后
                    System.out.println("偶数：" + number);
                    number++;
                    //唤醒奇数的线程
                    oddCondition.signal();

                } catch (Exception e) {
                    throw new RuntimeException();
                } finally {
                    lock.unlock();
                }
            }
        });
        oddThread.start();
        evenThread.start();
    }
}
